package com.sld.cloud.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 配置网关过滤器，实现了接口和注解后，不用在yml中配置
 */
@Component
public class MyLogGateWayFilter  implements GlobalFilter, Ordered {


    /**
     * 过滤器规则
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("自定义过滤器执行了");
        String uname = exchange.getRequest().getQueryParams().getFirst("uname");
        if (uname == null){
            System.out.println("用户名不存在，不能登录");
            // 设置相应状态码
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            // 完成响应
            exchange.getResponse().setComplete();
        }
        // 放行
        return chain.filter(exchange);
    }

    // 过滤器优先级，返回值小的先执行
    @Override
    public int getOrder() {
        return 0;
    }
}
